var config = require('config.js')
const app = getApp()

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function dateFormat(date) {
  Date.prototype.Format = function (fmt) {
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }
  var dateFmt = date.Format("yyyy-MM-dd");
  return dateFmt;
}

function validateData(value) {
  if (value == null || value == undefined || value == '') {
    return false
  }
  return true;
}

function showModel(msg) {
  wx.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success: function (res) {
    }
  })
}

function httpRequest(info) {
  // if (info.data == null) {
  //   info.data = {
  //     code: config.cfg.code
  //   }
  // } else {
  //   info.data['code'] = config.cfg.code
  // }
  var host = app.globalData.host
  var url = host + info.url
  // console.warn('url: ' + url)
  // console.warn(info.data)
  app.request({
    url: url,
    data: info.data,
    header: {
      'content-type': 'application/json' // 默认值
    },
    success: info.success,
    fail: info.fail,
    complete: info.complete
  })
}

function sayHello(name) {
  console.log(`Hello ${name} !` + config.cfg.a)
  var url = '/user/debug'
  var data = { 'key': 'ss' }
  // httpRequest(
  //   {
  //     url: url,
  //     data: data,
  //     success: function (res) {
  //       console.log(res)
  //     },
  //     fail: function (res) {
  //     },
  //     complete: function (res) {
  //       console.log('complete')
  //     }
  //   }
  // )
}



function payCard(cardId) {
  wx.getUserInfo({
    success: function (res) {
      doPayCard(cardId)
    }, fail() {
      wx.showModal({
        title: '错误',
        content: '请允许获取用户资料',
        showCancel: false,
        complete: function (res) {
          wx.openSetting({
            success: (res) => {
              /*
               * res.authSetting = {
               *   "scope.userInfo": true,
               *   "scope.userLocation": true
               * }
               */
            }
          })
        }
      })
    }
  })
}

function doPayCard(cardId) {

  var url = '/card/pay'
  var mark = ''
  // var openId = app.globalData.openId
  wx.showLoading({
    title: '支付中',
    mask: true
  })
  httpRequest({
    url: url,
    data: {
      cardId: cardId,
      // openId: openId,
      mark: mark,
    },
    header: {
      'content-type': 'application/json' // 默认值
    },
    success: function (res) {
      wx.hideLoading()
      var status = res.data.status
      if (status == 200) {
        // wx.showToast({
        //   title: '预约成功',
        //   icon: 'success',
        //   duration: 2000
        // })
      } else if (status == 201) {
        var response = res.data.info
        var nonce_str = response.nonce_str
        var prepay_id = response.result.prepay_id
        var sign = response.sign
        var timestamp = response.timeStamp
        wx.requestPayment({
          'appId': 'wx6d47db34d18f5e3a',
          'timeStamp': '' + timestamp,
          'nonceStr': '' + nonce_str,
          'package': 'prepay_id=' + prepay_id,
          'signType': 'MD5',
          'paySign': '' + sign,
          'success': function (res) {
            console.log(res)
            // submit()
            // toSuccessPage(bookDay, selectedTime, itemName, selectionName, userInfo, shopName)

            wx.reLaunch({
              url: '/pages/cardList/cardList',
            })
            return
          },
          'fail': function (res) {
            console.log('fail')
            wx.showModal({
              title: '错误',
              content: '支付失败.',
              showCancel: false
            })
            console.log(res)
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: res.data.msg,
          showCancel: false
        })
      }
    }, fail: function () {
      wx.showModal({
        title: '错误',
        content: '网络错误,请重试',
        showCancel: false
      })
    }
  })
}

function login() {
  app.auth()
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime,
  sayHello: sayHello,
  doPayCard: doPayCard,
  payCard: payCard,
  httpRequest: httpRequest,
  login: login,
  dateFormat: dateFormat,
  validateData: validateData,
  showModel: showModel
}
